import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = store.state.user.token
    if (token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(function(response) {
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么
  if (response.data.success) {
    // 操作成功
    return response.data
  } else {
    // 如果success为false 业务出错,直接触发reject
    // 被catch分支捕获
    return Promise.reject(new Error('请求错误'))
  }
}, function(error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  if (error.response) {
    if (error.response.data.code === 10002) {
      Message.error('登录已过期，请重新登录')
      store.commit('user/updateToken', '')
      store.commit('user/reomveUser')

      const url = encodeURIComponent(router.currentRoute.fullPath)
      router.push(`/login?url=${url}`)
    }
  } else {
    Message.error(error.response.data.message)
  }
  return Promise.reject(error)
})
export default service
